import os
import paramiko
import sys

serverIp = '192.168.0.158'
serverUser = 'root'
serverPassword = 'qdhlm.'
creatFileName = ''+sys.argv[2]+'-0.0.1-SNAPSHOT.xjar'
projectPath = 'D:/MyProject/hems-server/'+sys.argv[2]+'/'
localMkdirPath = projectPath + r'target/'

remoteFileMkdir = '/home/code/hems/server/'+sys.argv[2]+'/'
targetFileName = ''+sys.argv[2]+'-0.0.1-SNAPSHOT.xjar'
remoteFilePath = remoteFileMkdir + targetFileName
if sys.argv[1] == '124':
    serverIp = '124.70.68.52'
    serverPassword = 'qdHLM88983168'
if sys.argv[1] == '159':
    serverIp = '192.168.0.159'
    serverPassword = 'qdhlm.'

def remove_local():
    flag = os.path.exists(localMkdirPath + targetFileName)
    if flag:
        os.remove(localMkdirPath + targetFileName)
    flag = os.path.exists(localMkdirPath + targetFileName)
    if flag:
        os.remove(localMkdirPath + creatFileName);
    print


def mvn_package():
    os.chdir(projectPath)
    os.system('mvn clean')
    os.system('mvn package -Dmaven.test.skip=true')
    os.rename(localMkdirPath + creatFileName, localMkdirPath + targetFileName)
    print


def remove_remote():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(serverIp, username=serverUser, password=serverPassword, allow_agent=True)


def upload():
    t = paramiko.Transport((serverIp, 22))
    t.connect(username=serverUser, password=serverPassword)
    sftp = paramiko.SFTPClient.from_transport(t)
    sftp.put(localMkdirPath + targetFileName, remoteFilePath, put_call_back)
    t.close()
    print('上传成功')


def put_call_back(start, end):
    process = (float(start) / end) * 100


remove_local()
mvn_package()
remove_remote()
upload()
